#!/usr/bin/env python3

import os
import argparse
import glob


def find_lastest_target():

    # 递归获取当前目录下所有.cpp文件
    all_cpp_files = glob.glob(os.getcwd() + '/**/*.cpp', recursive=True)
    latest_file = None
    latest_mtime = 0
    # 搜索最新修改的cpp文件
    for file_path in all_cpp_files:
        mtime = os.path.getmtime(file_path)
        if mtime > latest_mtime:
            latest_mtime = mtime
            latest_file = file_path
    # 通过文件名获取target名称
    if latest_file is not None:
        tmp = latest_file.split('/')
        target = tmp[-2] + '_' + os.path.splitext(tmp[-1])[0]
        return target


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='简化命令输入')
    parser.add_argument('-cc',
                        action='store_true',
                        help='生成compile_commands.json文件')
    parser.add_argument('--list',
                        '-l',
                        action='store_true',
                        help='显示所有xmake targets')
    parser.add_argument('--run', '-r', action='store_true', help='编译最新的target')

    args = parser.parse_args()

    if args.cc:
        os.system('xmake project -k compile_commands build')
    elif args.list:
        os.system('xmake show -l targets')
    elif args.run:
        target = find_lastest_target()
        if target is not None:
            # xmake f --policies=run.autobuild 设置运行前自动构建
            os.system('xmake r ' + target)
